/*
 * Copyright (C),2015,北京新诺创科软件技术有限公司
 * author zhangmengliang
 */
package com.xnck.mfpms.interceptor;

import com.xiaoleilu.hutool.StrUtil;
import com.xnck.mfpms.annotation.AuthenPassport;
import com.xnck.mfpms.constant.ContextConstant;
import com.xnck.mfpms.entity.UserInfo;
import com.xnck.mfpms.service.UserService;
import com.xnck.mfpms.util.SessionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;


/**
 * 登录拦截器
 * @author zhangmengliang
 *
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {
	protected static final Logger log = Logger.getLogger(LoginInterceptor.class);

	@Autowired
	private UserService userService;
	
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {
        
    }
 
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView view) throws Exception {
		if (null != view){
			try {
				String curUserId = SessionUtils.getCurrentUserId(request);
				UserInfo curUser = userService.get(curUserId);
				if (null != curUser){
					view.addObject("curUser", curUser);
				}
			}
			catch (Exception e){
				log.error(e.toString());
			}
		}
    }
   
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    	//如果拦截的是方法，查验是否有AuthenPassport注解，如果有注解则需要验证用户是否已登录
    	if (handler instanceof HandlerMethod) {
    		HandlerMethod method = (HandlerMethod)handler;
        	AuthenPassport authPassport = method.getMethodAnnotation(AuthenPassport.class);
        	if (authPassport == null || authPassport.validate() == false) {
    			return true;
    		}
        	String userId;
        	try {
        		 userId = SessionUtils.getCurrentUserId(request);
			} catch (Exception e) {
				log.error(e.toString());
				userId = null;
			}
        	if (StrUtil.isNotBlank(userId)) {
				return true;
			}
            String loginUrl = request.getContextPath() + "/login.html";
            StringBuffer requestUrl = request.getRequestURL();
            if (StrUtil.isNotBlank(request.getQueryString())){
                requestUrl.append("?").append(request.getQueryString());
            }
            String returnUrl = URLEncoder.encode(requestUrl.toString(), "utf-8");
            loginUrl = loginUrl + "?f=" + ContextConstant.VALUE_SESSION_OUT + "&url=" + returnUrl;
			response.sendRedirect(loginUrl);
        	return false;
		}
    	return true;
    }
}
